<template>
  <el-container>
    <my-theme-card>
      <el-header>
        <my-title :title="edit ? '笔记修改':'笔记添加'" />
      </el-header>
      <el-main>

        <el-tabs v-model="currentTabPane" type="border-card">
          <el-tab-pane label="笔记信息" name="1">
            <el-divider content-position="left">笔记本名称</el-divider>
            <el-row>
              <el-cloumn :span="24">
                <el-input v-model="tempNote.name" style="width:200px;" />
              </el-cloumn>
            </el-row>
            <el-divider content-position="left">笔记内容</el-divider>
            <el-row>
              <el-col :span="12">
                <textarea v-model="originContent" style="width:100%;min-height: 500px;border:none;background-color: #cccccc3d;" /></el-col>
              <el-col :span="12"><div class="grid-content bg-purple-light">
                <div style="width:100%;min-height: 500px;background-color: #ecf5ff57;overflow: auto;" v-html="htmlContent" />
              </div></el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="分类信息" name="2">
            <el-divider content-position="left">笔记本</el-divider>
            <el-input v-model="notebook.name" style="width:150px;" @focus="dialogNoteBookVisible = true" />

            <el-divider content-position="left">分类</el-divider>
            <el-checkbox-group v-model="noteCategories">
              <el-checkbox v-for="noteCategory in categoryList" :key="noteCategory.id" :label="noteCategory.id">{{ noteCategory.name }}</el-checkbox>
            </el-checkbox-group>

            <el-divider content-position="left">标签</el-divider>
            <el-tag
              v-for="tag in noteLabels"
              :key="tag.id"
              style="margin-left:5px;"
              closable
              :disable-transitions="false"
              @close="removeLabel(tag)"
            >
              {{ tag.name }}
            </el-tag>
            <el-input
              v-if="labelAddVisible"
              ref="saveTagInput"
              v-model="labelValue"
              style="max-width:80px;"
              class="input-new-tag"
              @keyup.enter.native="handleLabelConfirm"
              @blur="handleLabelConfirm"
            />
            <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>

            <el-divider content-position="left">是否发布</el-divider>
            <el-switch
              v-model="tempNote.release"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />

            <el-divider content-position="left">描述信息</el-divider>
            <el-input v-model="tempNote.description" type="textarea" />

            <el-divider content-position="left">文本预览信息</el-divider>
            <el-input v-model="tempNote.preview" type="textarea" />

          </el-tab-pane>
        </el-tabs>
        <el-row style="text-align: center;margin-top:20px;">
          <el-button type="primary" @click="updateTask">确 定</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-row>
      </el-main>
    </my-theme-card>

    <el-dialog
      title="笔记本选择"
      :visible.sync="dialogNoteBookVisible"
      width="50%"
    >
      <div>
        <div v-for="item in notebookList" :key="item.id" style="width:100%;height:50px;margin:2px 0 2px 0;background: #e8f3fe;color: #7dbcfc;line-height:50px;text-align: center;" @click="chooseNoteBook(item)">{{ item.name }}</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogNoteBookVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogNoteBookVisible = false">确 定</el-button>
      </span>
    </el-dialog>

  </el-container>
</template>
<script>
import request from '@/utils/request'
import marked from 'marked'

export default {
  props: {
    edit: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      default: () => {}
    }
  },
  data: function() {
    return {
      // 笔记
      tempNote: {},
      // 笔记内容
      originContent: '',
      currentTabPane: '1',
      // 笔记的分类
      noteCategories: [],
      // 笔记的标签
      noteLabels: [],
      // 分类列表 对于key value
      categoryList: [],
      // 笔记本列表
      notebookList: [],
      // 选择的笔记本
      notebook: {},
      // 当前输入的标签值
      labelValue: '',
      // 笔记本选择
      dialogNoteBookVisible: false,
      // 标签输入框是否课件
      labelAddVisible: false
    }
  },
  computed: {
    noteCategoriesLabel() {
      const cgs = this.categoryList.filter(item => {
        let next = false
        this.noteCategories.forEach(item2 => {
          if (item2 === item.id) next = true
        })
        return next
      })
      return cgs
    },
    htmlContent: function() {
      return marked(this.originContent)
    }
  },
  watch: {
    row: {
      handler: function(note) {
        this.tempNote = note
      },
      immediate: true
    }
  },
  created() {
    this.directoryUpdate()
    this.init()
  },
  methods: {
    init: function() {
      this.noteInit()
      this.queryNoteContent()
    },
    // 字典更新
    directoryUpdate: function() {
      this.$store.commit('directory/setDirectory', 'logic')
    },
    // 取消
    cancel: function() {
      this.$emit('toChangePage', 'list')
    },
    // 添加笔记任务
    updateTask: function() {
      this.$progress.start()
      this.updateNotePreview()
      request({
        url: this.edit ? '/notebook/note/editAll' : '/notebook/note/addAll',
        method: 'post',
        data: {
          note_note: this.tempNote,
          notebook: this.notebook,
          mdContent: this.originContent,
          noteCategories: this.noteCategoriesLabel,
          noteLabels: this.noteLabels
        }
      }).then(res => {
        this.$progress.done()
        if (res.result) {
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      }
      ).catch(() => {
        this.$progress.done()
      })
    },
    // 初始化笔记本
    noteInit: function() {
      this.$progress.start()
      request({
        url: '/notebook/note/initNote',
        method: 'post',
        data: this.tempNote
      }).then(res => {
        this.$progress.done()
        if (res.result) {
          const data = res.data
          this.transformToData(data)
        } else {
          this.$message.error(res.msg)
        }
      }
      ).catch(() => {
        this.$progress.done()
      })
    },
    // 选择笔记本
    chooseNoteBook: function(row) {
      this.notebook = row
      this.dialogNoteBookVisible = false
    },
    // 将获取的数据转化为vue所用数据
    transformToData: function(res) {
      const data = res
      const noteCategories = []
      if (data.noteCategories) {
        data.noteCategories.forEach((item) => {
          noteCategories.push(item.id)
        })
      }
      if (data) {
        // 待选列表
        this.notebookList = data.notebookList || []
        this.categoryList = data.categoryList || []
        // 已选列表
        this.notebook = data.notebook || {}
        this.noteCategories = noteCategories || []
        this.noteLabels = data.noteLabels || []
      }
    },
    // 移除选择的标签
    removeLabel: function(label) {
      this.noteLabels = this.noteLabels.filter((item) => {
        return !(label.id === item.id || label.name === item.name)
      })
    },
    // 确定输入的标签
    handleLabelConfirm: function() {
      const inputValue = this.labelValue
      if (inputValue) {
        let next = true
        this.noteLabels.forEach(item => {
          if (item.name === inputValue)next = false
        })
        if (next) {
          this.noteLabels.push({
            name: inputValue
          })
        }
      }
      this.labelAddVisible = false
      this.labelValue = ''
    },
    showInput() {
      this.labelAddVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    queryNoteContent: function() {
      if (!this.tempNote || !this.tempNote.id) return
      request({
        url: '/notebook/note/queryNoteContent',
        method: 'post',
        data: this.tempNote
      }).then(res => {
        if (res.result) {
          this.originContent = res.data
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => { console.log('done') })
    },
    // 更新笔记文本预览信息
    updateNotePreview: function() {
      if (!this.tempNote.preview && this.originContent) {
        this.tempNote.preview = this.originContent.substr(0, this.originContent.length > 140 ? 140 : this.originContent.length)
      }
    }
  }
}
</script>

<style>
  .option-content {
    padding-top:15px;
    padding-bottom: 15px;
  }
</style>
